package com.mingren.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mingren.annotation.AuthCheck;
import com.mingren.common.BaseResponse;
import com.mingren.common.DeleteRequest;
import com.mingren.common.ResultUtils;
import com.mingren.constant.UserConstant;
import com.mingren.exception.BusinessException;
import com.mingren.exception.ErrorCode;
import com.mingren.exception.ThrowUtils;
import com.mingren.model.domain.User;
import com.mingren.model.dto.userRequest.UserQueryRequest;
import com.mingren.model.dto.userRequest.UserRegisterRequest;
import com.mingren.model.dto.userRequest.UserLoginRequest;
import com.mingren.model.dto.userRequest.UserAddRequest;
import com.mingren.model.dto.userRequest.UserUpdateRequest;
import com.mingren.model.vo.LoginUserVo;
import com.mingren.model.vo.UserVO;
import com.mingren.service.UserService;
import com.mingren.utils.encryptionUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

/**
 * @author 曹宏福
 * @version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 用户注册接口
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        //判空
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.NULL_ERROR);
        //注册接口调用
        long result = userService.userRegister(userRegisterRequest.getUserAccount(), userRegisterRequest.getUserPassword(), userRegisterRequest.getCheckPassword());
        return ResultUtils.success(result);
    }

    /**
     * 用户注册接口
     *
     * @param userLoginRequest
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public BaseResponse<LoginUserVo> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        //判空
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.NULL_ERROR);
        //注册接口调用
        LoginUserVo loginUserVo = userService.userLogin(userLoginRequest.getUserAccount(), userLoginRequest.getUserPassword(), request);
        //返回脱敏后的用户
        return ResultUtils.success(loginUserVo);
    }

    /**
     * 获取当前登录用户接口
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户信息")
    public BaseResponse<LoginUserVo> getLoginUser(HttpServletRequest request) {
        //1、获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        //2、将登录用户脱敏
        LoginUserVo loginUserVO = userService.getLoginUserVO(loginUser);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户注销
     * 可以从request请求对象对应的Session中获取登录用户信息、来完成用户注销、移除当前用户的登录态
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出当前用户登录态")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        boolean b = userService.userLogout(request);
        return ResultUtils.success(b);
    }

    /**
     * 创建用户（仅管理员）
     * mustRole = UserConstant.ADMIN_ROLE : 必须为管理员才能调用这个接口
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "创建用户（管理员接口）")
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 管理员添加用户的默认密码 12345678
        final String DEFAULT_PASSWORD = "12345678";
        String encryptPassword = encryptionUtils.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        //如果保存用户失败
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "保存用户失败");
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（仅管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "根据ID获取用户（管理员接口）")
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NULL_ERROR, "请求用户为空");
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    @ApiOperation(value = "根据ID获取脱敏后的用户信息")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        //返回脱敏后的单体用户信息
        return ResultUtils.success(userService.getUserVo(user));
    }

    /**
     * 删除用户（仅管理员）
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除用户（管理员接口）")
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户（仅管理员）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新用户（管理员接口）")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "更新用户失败");
        return ResultUtils.success(true);
    }


    /**
     * 分页获取用户封装列表（仅管理员）
     *
     * @param userQueryRequest 查询请求参数
     */
    @PostMapping("/list/page/vo")
    @ApiOperation(value = "分页获取用户（管理员接口）")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        //通过getQueryWrapper 获取将查询请求转为QueryWrapper的对象
        QueryWrapper<User> queryWrapper = userService.getQueryWrapper(userQueryRequest);
        //获取分页用户信息
        Page<User> userPage = userService.page(new Page<>(current, pageSize), queryWrapper);
        //获取
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVoList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }


}
